import requests
import json
import time

import pysnowball.cons as cons
import pysnowball.token as token


def fetch(url,headers=None):
    if headers is None:  
        headers = {
        "Host": "stock.xueqiu.com",
        "Accept": "application/json",
        "Cookie": token.get_token(),
        "User-Agent": "Xueqiu iPhone 11.8",
        "Accept-Language": "zh-Hans-CN;q=1, ja-JP;q=0.9",
        "Accept-Encoding": "br, gzip, deflate",
        "Connection": "keep-alive",
    }

    response = requests.get(url, headers=headers)

    # print(url)
    # print(HEADERS)
    # print(response)
    # print(response.content)

    if response.status_code != 200:
        raise Exception(response.content)

    return json.loads(response.content)


def fetch_without_token(url,headers=None):
    if headers is None:
        headers = {
        "Host": "stock.xueqiu.com",
        "Accept": "application/json",
        "User-Agent": "Xueqiu iPhone 11.8",
        "Accept-Language": "zh-Hans-CN;q=1, ja-JP;q=0.9",
        "Accept-Encoding": "br, gzip, deflate",
        "Connection": "keep-alive",
    }

    response = requests.get(url, headers=headers)

    # print(url)
    # print(HEADERS)
    # print(response)
    # print(response.content)

    if response.status_code != 200:
        raise Exception(response.content)

    return json.loads(response.content)


def get_stamp_from_time(time_str: str) -> int:
    """
    
    Convert a date string to a timestamp in milliseconds.
    
    Parameters
    ==========
    time_str : str
        The date string in the format "YYYY-MM-DD".

    Returns
    =======
    int
        The timestamp in milliseconds.
        
    Examples
    ========
    >>> get_stamp_from_time("2025-05-16")   
    1718208000000
    
    """
    return int(time.mktime(time.strptime(time_str, "%Y-%m-%d"))) * 1000


def get_time_from_stamp(time_stamp: int) -> str:
    if time_stamp >= 10**10:
        time_stamp = int(time_stamp / 1000)
    return time.strftime("%Y-%m-%d,%H:%M:%S", time.localtime(time_stamp))

def is_hk_symbol(symbol):
    if len(symbol) == 5 and symbol.isdigit():
        return True
    else:
        return False
